/**
 * 
 */
package com.feib.stms.action;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.feib.stms.model.Securities;
import com.feib.stms.model.User;
import com.feib.stms.pagination.PaginatedList;
import com.feib.stms.service.SecuritiesService;
import com.feib.stms.util.UserUtil;

/**
* @title (#)Stms9010ActionBean.java<br>
 * @description 券商分公司資料維護 <br>
 * @author Karl Chen<br>
 * @version 1.0.0 2012/05/28
 * @2012/05/28 create by Karl Chen<br>
 *
 */
public class Stms9010ActionBean extends BaseActionBean 
{	
	private static final long serialVersionUID = 5081153126692577389L;
	
	private static final String DEFAULT_JSP = "/WEB-INF/views/stms9010/stms9010.jsp";
    private static final String DETAIL_JSP = "/WEB-INF/views/stms9010/stms9010Detail.jsp";
    private static final String CREATE_JSP = "/WEB-INF/views/stms9010/stms9010Create.jsp";
    
    /*畫面sortHeader傳回來的值*/
	private static List<String> SORT_KEYS = new ArrayList<String>();
	static{
		//分公司代號
		SORT_KEYS.add("securitiesNo".toLowerCase());
		//分公司名稱
		SORT_KEYS.add("securitiesName".toLowerCase());
		//聯絡人
		SORT_KEYS.add("contactName".toLowerCase());
		//電話號碼
		SORT_KEYS.add("contactTelno".toLowerCase());
		//手機號碼
		SORT_KEYS.add("contactCellno".toLowerCase());
		//Email
		SORT_KEYS.add("contactEmail".toLowerCase());
		//地址
		SORT_KEYS.add("securitiesAddress".toLowerCase());
	}

	/*使用SORT_KEYS作key值取得對應的資料庫欄位名稱*/
	private static Map<String,String> SORT_FIELD =  new HashMap<String, String>();
	static{
		//分公司代號
		SORT_FIELD.put("securitiesNo".toLowerCase(),"SECURITIES_NO");
		//分公司名稱
		SORT_FIELD.put("securitiesName".toLowerCase(),"SECURITIES_NAME");
		//聯絡人
		SORT_FIELD.put("contactName".toLowerCase(),"CONTACT_NAME");
		//電話號碼
		SORT_FIELD.put("contactTelno".toLowerCase(),"CONTACT_TELNO");
		//手機號碼
		SORT_FIELD.put("contactCellno".toLowerCase(),"CONTACT_CELLNO");
		//Email
		SORT_FIELD.put("contactEmail".toLowerCase(),"CONTACT_EMAIL");
		//地址
		SORT_FIELD.put("securitiesAddress".toLowerCase(),"SECURITIES_ADDRESS");
	}
    
    /**
     * 查詢條件-分公司代號
     */
    private String qrySecuritiesIdForm;

    /**
     * 查詢條件-分公司名稱
     */
    private String qrySecuritiesNameForm;
    
    /**
     * 查詢結果(多筆)
     */
    private PaginatedList<Securities> queryResult;
    
    /**
     * 更新-綁定查詢條件
     */
    @Validate( required=true, on={"doViewDetail"})
    private Long qrySecuritiesPk;
    
    /**
     * 新增綁定Securities
     */
    private Securities createSecurities;
    
    /**
     * 更新/刪除-綁定Securities
     */
    private Securities viewSecurities;
    
    /**
     * 執行結果信息
     */
    private String message;
    
    @SpringBean("securitiesService")
    private SecuritiesService securitiesService;
       
    @DontBind
    @DefaultHandler
    public Resolution doDefault()
    {
        logger.debug("Enter doDefault mehtod.");
        return new ForwardResolution(DEFAULT_JSP); 
    }
    
    /**
     * 查詢
     * @return
     */
    public Resolution doQuery()
    {
        logger.debug("Enter doQuery mehtod.");
        //logger.debug("qryMenuTypeIdForm={}, qryMenuIdForm={}, qryActionNameForm={} ", new Object[]{qryMenuTypeIdForm, qryMenuIdForm, qryActionNameForm });
        
        /* 設定換頁、排序等條件*/
        PaginatedList<Securities> qryCondition = new PaginatedList<Securities>();
        String sortCriterion = "SECURITIES_NO";
        int sortDirection = 1;
        if(null != queryResult) {
        	sortCriterion = queryResult.getSortCriterion();
        	sortDirection = queryResult.getSortDirection();
        	logger.debug(" sortCriterion={}  sortDirection={} ", new Object[]{queryResult.getSortCriterion(), queryResult.getSortDirection()});
        	qryCondition.setPageNumber(queryResult.getPageNumber());
			qryCondition.setPageSize(queryResult.getPageSize());
			String StringSortCriterion=SORT_FIELD.get(sortCriterion.toLowerCase());
			qryCondition.setSortCriterion(StringSortCriterion);
			qryCondition.setSortDirection(sortDirection);
			logger.debug(" qryCondition:sortCriterion={}  sortDirection={} ", new Object[]{qryCondition.getSortCriterion(), qryCondition.getSortDirection()});
        }
        
        /*沒有設定排序就以第一欄作排序條件*/
		if (null == queryResult || StringUtils.isEmpty(queryResult.getSortCriterion()) || !SORT_KEYS.contains(queryResult.getSortCriterion().toLowerCase()))
		{
			qryCondition.setSortCriterion(SORT_FIELD.get(SORT_KEYS.get(0)));
		}
        //封裝查詢條件
        Securities securities = new Securities();
        //分公司代號
        securities.setSecuritiesNo(this.qrySecuritiesIdForm);
        //分公司名稱
        securities.setSecuritiesName(this.qrySecuritiesNameForm);
        
        User user = UserUtil.getUser();    	
    	//群組
        securities.setGroup(user.getGroup());
        
        //調用service,到資料庫撈取DB
        queryResult = securitiesService.findForPaginatedListBySecurities(securities, qryCondition); 
        
        /* 重新計算頁面頁數 */
        if(null != this.queryResult && !"0".equals(queryResult.getPageSize())){
	        int tempSize = (queryResult.getFullListSize() % queryResult.getPageSize()) == 0 
	        			? (queryResult.getFullListSize() / queryResult.getPageSize())
	        			:((queryResult.getFullListSize() / queryResult.getPageSize())+1);        
	        queryResult.setFullListSize(tempSize);
        }
        
        if (null == this.queryResult)
        	this.queryResult = qryCondition;
        
        queryResult.setSortCriterion(sortCriterion);
		queryResult.setSortDirection(sortDirection);
        
        //result
        if (CollectionUtils.isEmpty(this.queryResult.getPaginatedList()))
        	this.message = "查無資料！";
        
        return new ForwardResolution(DEFAULT_JSP); 
    }
    
    
    /**
     * 跳轉新增畫面
     * @return
     */
    public Resolution doInitCreate()
    {	
    	logger.debug("Enter doInitCreate mehtod.");
    	//將畫面下拉選單上層程式列表查詢出來
    	//menuItems = menuItemService.initMenuItemOptionList();
    	return new ForwardResolution(CREATE_JSP); 
    }
    
    /**
     * 新增
     * @return
     */
    public Resolution doCreate()
    {	
    	logger.debug("Enter doCreate mehtod.");
    	User user = UserUtil.getUser();   
    	//檢查是否重複
    	if(createSecurities != null && createSecurities.getSecuritiesNo() != null){
    		int queryCount = securitiesService.countSecuritiesNo(createSecurities.getSecuritiesNo());
    		if(queryCount > 0){
    			this.message = "新增失敗,分公司代碼重複!";
    			return new ForwardResolution(CREATE_JSP); 
    		}
    	}
    	//群組
    	createSecurities.setGroup(user.getGroup());
    	//母公司
    	Securities tempSecurities = user.getSecurities();
    	long parentSecuritiesPk = securitiesService.findParentSecuritiesPk(user.getGroup().getGroupPk());
    	if(parentSecuritiesPk == -1){
    		message = "該帳戶下沒有母公司,請與管理員聯繫";
    		return new ForwardResolution(CREATE_JSP);
    	}
    	tempSecurities.setSecuritiesPk(parentSecuritiesPk);    	
    	createSecurities.setParentSecurities(tempSecurities);
    	//創建者
    	createSecurities.setCreatedBy(user.getGroup().getGroupNo()+"_"+user.getUserId());
    	//創建時間
    	createSecurities.setCreatedDate(new Date());
    	
    	int insertCount = securitiesService.saveSecurities(createSecurities);
    	
    	message = insertCount > 0?"新增成功！":"新增失敗!";
    	if(insertCount > 0){//新增成功，則跳轉到查詢畫面
    		return doQuery();
    	}
    	return new ForwardResolution(CREATE_JSP); 
    }
    
    /**
     * 跳轉更新畫面
     * @return
     */
    public Resolution doViewDetail()
    {
        logger.debug("Enter doViewDetail mehtod.");
    	//根據pk查詢出該筆資料
        viewSecurities = securitiesService.getBySecuritiesPk(this.qrySecuritiesPk);
        return new ForwardResolution(DETAIL_JSP); 
    }
    
    /**
     * 更新
     * @return
     */
    public Resolution doUpdate()
    {
        logger.debug("Enter doUpdate mehtod.");
        User user = UserUtil.getUser();
//      檢查是否重複
    	if(createSecurities != null && createSecurities.getSecuritiesNo() != null){
    		int queryCount = securitiesService.countSecuritiesNo(createSecurities.getSecuritiesNo());
    		if(queryCount > 0){
    			this.message = "更新失敗,分公司代碼重複!";
    			return new ForwardResolution(DETAIL_JSP); 
    		}
    	}
        String updateUser = user.getGroup().getGroupNo()+"_"+user.getUserId();
    	//創建者
    	viewSecurities.setUpdatedBy(updateUser);
    	//創建時間
    	viewSecurities.setUpdatedDate(new Date());
        int insertCount = securitiesService.updateSecurities(viewSecurities);        
    	message = insertCount > 0?"更新成功！":"更新失敗!";
    	if(insertCount > 0){//更新成功，則跳轉到查詢畫面
    		return doQuery();
    	}
        return new ForwardResolution(DETAIL_JSP); 
    }

    /**
     * 匯出Excel檔案
     * @return
     */
    public Resolution doExportExcel()
    {
    	try {
    		
    		// TODO: 產生Excel
    		String downloadFilePath = "";
    		
    		File downloadFile = new File(downloadFilePath);
            byte[] bytes = new byte[(int)downloadFile.length()];
            
            BufferedInputStream bufferedInputStream = 
                new BufferedInputStream(new FileInputStream(downloadFile)); 

            bufferedInputStream.read(bytes);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            inputStream.close();
            bufferedInputStream.close();

            String isoFileName = new String("上傳記錄查詢結果.xls".getBytes("MS950"), "ISO8859-1");

            StreamingResolution streamingResolution = new StreamingResolution("application/vnd.ms-excel",inputStream).setFilename(isoFileName);

            return streamingResolution;
		} catch (Exception e) {
            logger.error("", e);
		}
        return new ForwardResolution(DEFAULT_JSP); 
    }
    
	/**
	 * @return message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message 的設定的 message
	 */
	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * @return qrySecuritiesIdForm
	 */
	public String getQrySecuritiesIdForm() {
		return qrySecuritiesIdForm;
	}

	/**
	 * @param qrySecuritiesIdForm 的設定的 qrySecuritiesIdForm
	 */
	public void setQrySecuritiesIdForm(String qrySecuritiesIdForm) {
		this.qrySecuritiesIdForm = qrySecuritiesIdForm;
	}

	/**
	 * @return qrySecuritiesNameForm
	 */
	public String getQrySecuritiesNameForm() {
		return qrySecuritiesNameForm;
	}

	/**
	 * @param qrySecuritiesNameForm 的設定的 qrySecuritiesNameForm
	 */
	public void setQrySecuritiesNameForm(String qrySecuritiesNameForm) {
		this.qrySecuritiesNameForm = qrySecuritiesNameForm;
	}

	/**
	 * @return queryResult
	 */
	public PaginatedList<Securities> getQueryResult() {
		return queryResult;
	}

	/**
	 * @param queryResult 的設定的 queryResult
	 */
	public void setQueryResult(PaginatedList<Securities> queryResult) {
		this.queryResult = queryResult;
	}

	/**
	 * @return createSecurities
	 */
	public Securities getCreateSecurities() {
		return createSecurities;
	}

	/**
	 * @param createSecurities 的設定的 createSecurities
	 */
	public void setCreateSecurities(Securities createSecurities) {
		this.createSecurities = createSecurities;
	}

	/**
	 * @return qrySecuritiesPk
	 */
	public Long getQrySecuritiesPk() {
		return qrySecuritiesPk;
	}

	/**
	 * @param qrySecuritiesPk 的設定的 qrySecuritiesPk
	 */
	public void setQrySecuritiesPk(Long qrySecuritiesPk) {
		this.qrySecuritiesPk = qrySecuritiesPk;
	}

	/**
	 * @return viewSecurities
	 */
	public Securities getViewSecurities() {
		return viewSecurities;
	}

	/**
	 * @param viewSecurities 的設定的 viewSecurities
	 */
	public void setViewSecurities(Securities viewSecurities) {
		this.viewSecurities = viewSecurities;
	}
}
